import React, { useState, useEffect } from 'react'
import moment from 'moment'
import { Form, Input, Button, message, Checkbox, Table } from 'antd'
import { CheckOutlined, CloseOutlined } from '@ant-design/icons'
import { useHistory, useParams } from 'react-router-dom'
import { getUserById, updateUserById } from '@/api/user'
import { getUserOrders } from '@/api/order'
import { typeOrder, updateUserProps } from '@/types/user'
import { typeOrderProductItem } from '../../../types/cart'
import './index.scss'

const pageSize = 10
const UserInfo = () => {
  const history = useHistory()
  const { userId } = useParams<{userId:string}>()
  const [userInfo, setUserInfo]:[any, any] = useState(null)
  const [orders, setOrders]:[any, any] = useState([])
  const [current, setCurrent] = useState(1)
  const [total, setTotal] = useState(0)

  useEffect(() => {
    loadUserInfo()
    loadUserOrders(1)
  }, [])

  const loadUserInfo = async() => {
    const res = await getUserById(userId)

    setUserInfo(res.data)
    console.log(res.data)
  }

  const loadUserOrders = async(pageNum:number = current) => {
    const res = await getUserOrders(userInfo.id, {
      pageNum,
      pageSize
    })

    setOrders(res.data.orders)
    setTotal(res.data.total)
    setCurrent(pageNum)
    console.log(res.data.orders[ 0 ])
  }

  /**
   * 更新用户信息
   */
  const onclickUpdate = async({ email, name, isAdmin }: updateUserProps) => {
    try {
      await updateUserById(userId, {
        name,
        email,
        isAdmin,
      })

      message.success('修改用户信息成功')
    } catch (err) {
      console.log(err)
    }
  }

  const columns = [
    {
      title: '创建时间',
      key: 'createdAt',
      render: (text: string) => (
        <span>{moment(text).format('YYYY/MM/DD')}</span>
      )
    },
    {
      title: '用户名',
      key: 'user',
      render: (text: string, record: typeOrder) => (
        <span>{record.user.name}</span>
      )
    },
    {
      title: '商品内容',
      dataIndex: 'product',
      render: (text: string, record: typeOrder) => (
        <div>
          {record.productsItems.map((item:typeOrderProductItem) => (
            <div key={item._id}><strong>{item.name}</strong> * {item.qty}</div>
          ))}
        </div>
      )
    },
    {
      title: '价格',
      key: 'price',
      render: (text: string, record: typeOrder) => (
        <div>
          {record.productsPrice} + {record.shippingPrice} = {record.totalPrice}
        </div>
      )
    },
    {
      title: '支付状态',
      dataIndex: 'isPaid',
      render: (text: string, record:typeOrder) => (
        <div>
          {
            record.isPaid
              ? <CheckOutlined style={{ color: '#7cb305' }} />
              : <CloseOutlined style={{ color: '#f5222d' }} />
          }
        </div>
      )
    },
    {
      title: '发货状态',
      dataIndex: 'isDelivered',
      render: (text: string, record:typeOrder) => (
        <div>
          {
            record.isPaid
              ? <CheckOutlined style={{ color: '#7cb305' }} />
              : <CloseOutlined style={{ color: '#f5222d' }} />
          }
        </div>
      )
    },
    {
      key: 'control',
      render: (text:string, record:typeOrder) => (
        <Button
          onClick={() => { history.push(`/admin/order/${ record._id }?authType=admin`) }}
        >
          查看详情
        </Button>
      )
    },
  ]

  return userInfo
    ? (
      <div className="admin-user-info">
        <div className="info">
          <h2>用户资料</h2>
          <Form
            autoComplete="off"
            initialValues={{ ...userInfo }}
            labelAlign="left"
            labelCol={{ span: 6 }}
            onFinish={onclickUpdate}
          >
            <Form.Item
              label="邮箱"
              name="email"
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="姓名"
              name="name"
            >
              <Input/>
            </Form.Item>
            <Form.Item
              label="管理员"
              name="isAdmin"
              valuePropName="checked"
            >
              <Checkbox
                checked={userInfo.isAdmin}
                onChange={(e) => setUserInfo({ ...userInfo, isAdmin: e.target.checked })}
              />
            </Form.Item>
            <Form.Item>
              <Button
                className="submit-btn"
                htmlType="submit"
                type="primary"
              >
              修改用户信息
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="orders">
          <h2>用户订单</h2>
          <Table
            columns={columns}
            dataSource={orders}
            pagination={{
              position: ['bottomRight'],
              pageSize,
              current,
              total,
              onChange: (current:number) => {
                loadUserOrders(current)
              }
            }}
            rowKey={(record:typeOrder) => record._id || ''}
          />
        </div>
      </div>
    )
    : null
}

export default UserInfo
